{% extends "admin/base.html" %}

{% block title %}创建量表 - 管理后台{% endblock %}

{% block extra_css %}
<style>
    .form-section {
        background: white;
        border-radius: 8px;
        padding: 24px;
        margin-bottom: 24px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    
    .form-section h5 {
        color: #2c3e50;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 2px solid #e9ecef;
    }
    
    .form-group {
        margin-bottom: 20px;
    }
    
    .form-label {
        font-weight: 600;
        color: #495057;
        margin-bottom: 8px;
    }
    
    .form-control, .form-select {
        border: 1px solid #ced4da;
        border-radius: 6px;
        padding: 10px 12px;
        transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
    }
    
    .form-control:focus, .form-select:focus {
        border-color: #80bdff;
        box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
    }
    
    .btn-primary {
        background-color: #007bff;
        border-color: #007bff;
        padding: 10px 24px;
        font-weight: 500;
    }
    
    .btn-secondary {
        background-color: #6c757d;
        border-color: #6c757d;
        padding: 10px 24px;
        font-weight: 500;
    }
    
    .alert {
        border-radius: 6px;
        margin-bottom: 20px;
    }
    
    .required {
        color: #dc3545;
    }
    
    .form-text {
        color: #6c757d;
        font-size: 0.875rem;
    }
    
    .loading {
        display: none;
    }
    
    .loading.show {
        display: inline-block;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="mb-1">创建量表</h2>
            <p class="text-muted mb-0">创建新的系统内置量表</p>
        </div>
        <a href="/admin-scales" class="btn btn-secondary">
            <i class="bi bi-arrow-left me-2"></i>返回量表列表
        </a>
    </div>

    <!-- 提示信息 -->
    <div id="alert-container"></div>

    <!-- 创建表单 -->
    <form id="createScaleForm">
        <!-- 基本信息 -->
        <div class="form-section">
            <h5><i class="bi bi-info-circle me-2"></i>基本信息</h5>
            
            <div class="row">
                <div class="col-md-8">
                    <div class="form-group">
                        <label for="title" class="form-label">量表标题 <span class="required">*</span></label>
                        <input type="text" class="form-control" id="title" name="title" required>
                        <div class="form-text">请输入量表的完整标题</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="category_id" class="form-label">量表分类 <span class="required">*</span></label>
                        <select class="form-select" id="category_id" name="category_id" required>
                            <option value="">请选择分类</option>
                        </select>
                    </div>
                </div>
            </div>
            
            <div class="form-group">
                <label for="subtitle" class="form-label">副标题</label>
                <input type="text" class="form-control" id="subtitle" name="subtitle">
                <div class="form-text">可选的副标题或简短描述</div>
            </div>
            
            <div class="form-group">
                <label for="description" class="form-label">量表描述 <span class="required">*</span></label>
                <textarea class="form-control" id="description" name="description" rows="4" required></textarea>
                <div class="form-text">详细描述量表的用途、适用人群等</div>
            </div>
            
            <div class="form-group">
                <label for="instruction" class="form-label">测评说明</label>
                <textarea class="form-control" id="instruction" name="instruction" rows="3"></textarea>
                <div class="form-text">向用户说明如何进行测评</div>
            </div>
        </div>

        <!-- 发布设置 -->
        <div class="form-section">
            <h5><i class="bi bi-gear me-2"></i>发布设置</h5>
            
            <div class="row">
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="status" class="form-label">发布状态</label>
                        <select class="form-select" id="status" name="status">
                            <option value="DRAFT">草稿</option>
                            <option value="PUBLISHED">已发布</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="min_member_level" class="form-label">会员级别要求</label>
                        <select class="form-select" id="min_member_level" name="min_member_level">
                            <option value="basic">基础会员</option>
                            <option value="professional">专业会员</option>
                            <option value="institution">机构会员</option>
                            <option value="research">研究会员</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="estimated_time" class="form-label">预估时间（分钟）</label>
                        <input type="number" class="form-control" id="estimated_time" name="estimated_time" min="1" max="120">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="version" class="form-label">版本号</label>
                        <input type="text" class="form-control" id="version" name="version" value="1.0">
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="is_public" name="is_public" checked>
                        <label class="form-check-label" for="is_public">
                            公开量表
                        </label>
                        <div class="form-text">是否在量表列表中公开显示</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="is_free" name="is_free" checked>
                        <label class="form-check-label" for="is_free">
                            免费量表
                        </label>
                        <div class="form-text">是否免费提供给用户使用</div>
                    </div>
                </div>
            </div>
            
            <div class="form-group" id="price-group" style="display: none;">
                <label for="price" class="form-label">价格（元）</label>
                <input type="number" class="form-control" id="price" name="price" min="0" step="0.01" value="0">
                <div class="form-text">付费量表的价格</div>
            </div>
        </div>

        <!-- 作者信息 -->
        <div class="form-section">
            <h5><i class="bi bi-person me-2"></i>作者信息</h5>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="author" class="form-label">作者</label>
                        <input type="text" class="form-control" id="author" name="author">
                        <div class="form-text">量表的原作者或编制者</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="copyright_info" class="form-label">版权信息</label>
                        <input type="text" class="form-control" id="copyright_info" name="copyright_info">
                        <div class="form-text">版权声明或授权信息</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="d-flex justify-content-end gap-3 mb-4">
            <a href="/admin-scales" class="btn btn-secondary">
                <i class="bi bi-x-circle me-2"></i>取消
            </a>
            <button type="submit" class="btn btn-primary">
                <span class="loading spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                <i class="bi bi-check-circle me-2"></i>创建量表
            </button>
        </div>
    </form>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 检查管理员认证
    const adminToken = localStorage.getItem('adminToken');
    if (!adminToken) {
        window.location.href = '/admin-portal';
        return;
    }
    
    // 加载分类列表
    loadCategories();
    
    // 绑定表单提交事件
    document.getElementById('createScaleForm').addEventListener('submit', handleSubmit);
    
    // 绑定免费选项变化事件
    document.getElementById('is_free').addEventListener('change', function() {
        const priceGroup = document.getElementById('price-group');
        if (this.checked) {
            priceGroup.style.display = 'none';
            document.getElementById('price').value = '0';
        } else {
            priceGroup.style.display = 'block';
        }
    });
});

// 加载分类列表
function loadCategories() {
    fetch('/api/admin/scales/categories', {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const categorySelect = document.getElementById('category_id');
            categorySelect.innerHTML = '<option value="">请选择分类</option>';
            
            const categories = data.data.categories || data.data;
            categories.forEach(category => {
                const option = document.createElement('option');
                option.value = category.id;
                option.textContent = category.name;
                categorySelect.appendChild(option);
            });
        } else {
            showAlert('加载分类列表失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('加载分类列表失败', 'error');
    });
}

// 处理表单提交
function handleSubmit(event) {
    event.preventDefault();
    
    const form = event.target;
    const formData = new FormData(form);
    const data = {};
    
    // 收集表单数据
    for (let [key, value] of formData.entries()) {
        if (key === 'is_public' || key === 'is_free') {
            data[key] = form.querySelector(`[name="${key}"]`).checked;
        } else if (key === 'category_id' || key === 'estimated_time') {
            data[key] = value ? parseInt(value) : null;
        } else if (key === 'price') {
            data[key] = value ? parseFloat(value) : 0;
        } else {
            data[key] = value.trim();
        }
    }
    
    // 验证必填字段
    if (!data.title) {
        showAlert('请输入量表标题', 'error');
        return;
    }
    
    if (!data.description) {
        showAlert('请输入量表描述', 'error');
        return;
    }
    
    if (!data.category_id) {
        showAlert('请选择量表分类', 'error');
        return;
    }
    
    // 显示加载状态
    const submitBtn = form.querySelector('button[type="submit"]');
    const loading = submitBtn.querySelector('.loading');
    loading.classList.add('show');
    submitBtn.disabled = true;
    
    // 提交数据
    fetch('/api/admin/scales', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('量表创建成功！', 'success');
            setTimeout(() => {
                window.location.href = '/admin-scales';
            }, 1500);
        } else {
            showAlert('创建失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('创建失败，请重试', 'error');
    })
    .finally(() => {
        // 隐藏加载状态
        loading.classList.remove('show');
        submitBtn.disabled = false;
    });
}

// 显示提示信息
function showAlert(message, type = 'info') {
    const alertContainer = document.getElementById('alert-container');
    const alertClass = type === 'error' ? 'alert-danger' : 
                      type === 'success' ? 'alert-success' : 'alert-info';
    
    const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;
    
    alertContainer.innerHTML = alertHtml;
    
    // 自动隐藏成功消息
    if (type === 'success') {
        setTimeout(() => {
            const alert = alertContainer.querySelector('.alert');
            if (alert) {
                alert.remove();
            }
        }, 3000);
    }
}
</script>
{% endblock %}